<template>
  <div v-loading="isloading" class="beian-container">
    <el-dialog :title="
        dialogStatus == 'add' ? '底图底数领取记录新增' : '底图底数领取记录编辑'
      " :visible.sync="isDialogShow" width="30%" :append-to-body="true" class="dialog1">
      <el-form ref="form" :model="form" :rules="rules" label-width="150px" label-position="left">
        <el-form-item label="行政区划选择:" prop="targetlist" v-if="dialogStatus == 'add'">
          <!-- <el-cascader
          style="width: 350px"
          v-model="citySelected"
          :options="countyList"
          :props="props"
          size="medium"
          placeholder="请选择关联村庄"
          clearable
          collapse-tags
          :show-all-levels="false"
          @change="handleChange"
          v-if="citySelectedShow"
        ></el-cascader> -->
          <el-select v-model="form.targetlist" multiple placeholder="请选择" size="mini">
            <el-option v-for="item in options" :key="item" :label="item" :value="item">
            </el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="行政区划选择:" prop="target" v-else>
          <el-select v-model="form.target" placeholder="请选择" size="mini">
            <el-option v-for="item in options" :key="item" :label="item" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="领取人:" prop="receiveName">
          <el-input type="text" :rows="2" placeholder="请输入内容" size="mini" clearable v-model="form.receiveName" style="width: 47%">
          </el-input>
        </el-form-item>
        <el-form-item label="领取时间:" prop="receiveDate">
          <el-date-picker v-model="form.receiveDate" type="date" placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="isDialogShow = false">取 消</el-button>
        <el-button type="primary" @click="dialogStatus === 'add' ? submitForm('form') : updateData()">提交</el-button>
      </span>
    </el-dialog>
    <div>
      <div class="header">
        <i class="el-icon-d-arrow-right"></i>底图底数领取新增
      </div>
      <div class="header-button">
        <el-tooltip class="item" effect="dark" :content="'未领取底图数' + options.length" placement="bottom-start">
          <el-badge :value="options.length" class="item" type="primary">
            <el-button type="danger" @click="open"><i class="el-icon-plus"></i>添加
            </el-button>
          </el-badge>
        </el-tooltip>
        <el-button type="primary" @click="download"><i class="el-icon-download"></i>导出</el-button>
      </div>
    </div>
    <div class="header">
      <i class="el-icon-d-arrow-right"></i>底图底数领取备案
    </div>
    <el-table :data="tableData" stripe border style="width: 100%" class="eltable">
      <el-table-column label="序号" width="80" type="index" />
      <el-table-column prop="area" label="用户范围" width="220">
        <template slot-scope="scope">
          <span v-if="scope.row.area == ''">湖南省</span>
        </template>
      </el-table-column>
      <el-table-column prop="target" label="行政单位" />
      <el-table-column prop="receiveName" label="领取人 " width="150" />
      <el-table-column prop="receiveDate" label="领取时间 " width="180" />
      <el-table-column label="操作" width="225" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button type="primary" @click="handleUpdate(scope.row)" size="mini" plain><i class="el-icon-edit"></i>编辑
          </el-button>
          <el-button type="danger" @click="handleDelete(scope.row.id)" size="mini" plain><i class="el-icon-delete"></i>删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-if="tableData.length > 0" class="elpagi" :total="total" @size-change="getdata" @current-change="getdata" @prev-click="getdata" @next-click="getdata" :current-page.sync="listquery.currentPage" :page-sizes="[10, 20, 30, 40]" :page-size.sync="listquery.pageSize" layout="total,sizes, prev, pager, next, jumper" />
  </div>
</template>
<script>
import {
  getlist,
  getcitylist,
  getcountrylist,
  getvillagelistskip,
  add,
  edit,
  del,
} from "@/api/record.js";

import { handleCofirm } from "@/utils/confirm";

export default {
  data () {
    return {
      targetlist: [],
      total: 0,
      dialogStatus: "",
      options1: [],
      // citySelected: "",
      // countyList: citys.children,
      // citySelectedShow:true,
      //  props: {
      //   lazy: true,
      //   lazyLoad(node, resolve) {
      //     let level = node.level;
      //     if (level == 2) {
      //       let country = node.label;
      //       let city = node.parent.label;
      //       getTownList({
      //         city: city,
      //         country: country,
      //       }).then((res) => {
      //         let nodes = [];
      //         let promiseArrary = [];
      //         res.data.map((v, i) => {
      //           let n = {
      //             id: i,
      //             label: v,
      //             value: v,
      //             children: [],
      //           };
      //           let promise = getAllVillageList({
      //             city: city,
      //             country: country,
      //             town: v,
      //           }).then((response) => {
      //             return response;
      //           });
      //           promiseArrary.push(promise);
      //           nodes.push(n);
      //         });
      //         Promise.all(promiseArrary).then((dataArr) => {
      //           nodes.forEach((v, i) => {
      //             let data = dataArr[i];
      //             v.children = data.data.map((item, index) => {
      //               return {
      //                 id: index,
      //                 label: item.name,
      //                 value: item.id + "," + item.name,
      //                 leaf: true,
      //               };
      //             });
      //           });
      //           resolve(nodes);
      //         });
      //       });
      //     } else {
      //       resolve(node);
      //     }
      //   },
      //   multiple: true,
      // },
      form: {
        area: "",
        target: "",
        targetlist: [],
        receiveName: "",
        receiveDate: "",
      },
      rules: {
        targetlist: [
          { required: true, message: "请选择领取区域", trigger: "blur" },
        ],
        receiveName: [
          { required: true, message: "请输入领取人名称", trigger: "blur" },
        ],
        receiveDate: [
          { required: true, message: "请选择领取时间", trigger: "blur" },
        ],
      },
      tableData: [],
      options: [],
      isloading: false,
      role: "",
      nowuserarea: "",
      isDialogShow: false,
      listquery: {
        pageSize: 10,
        currentPage: 1,
      },
    };
  },
  mounted () {
    this.getdata();
    this.role = this.$store.getters.user.roles[0].name;
    if (this.role == "湖南省第三测绘院" || this.role == "超级管理员") {
      this.getcitylistv();
    } else {
      this.nowuserarea = this.$store.getters.user.area;
      this.form.area = this.nowuserarea;
      let list = this.nowuserarea.split("-");

      if (this.role == "市州用户") {
        this.getcountrylistv(list[0]);
      } else {
        this.getvillagelistskipv(list[0], list[1]);
      }
    }
  },
  methods: {
    handleChange (e) {

    },
    async getcitylistv () {
      let res = await getcitylist();
      this.options1 = res.data;
    },
    download () { },
    async getcountrylistv (city) {
      let res = await getcountrylist(city);
      this.options1 = res.data;
    },
    async getvillagelistskipv (city, country) {
      let res = await getvillagelistskip(city, country);
      this.options1 = res.data;
    },
    async getdata () {
      this.isloading = true;
      let res = await getlist(this.listquery);
      this.tableData = res.data.content;
      this.total = res.data.totalElements;
      this.target2 = res.target;
      this.options = [];
      this.options1.forEach((element) => {
        if (this.target2.indexOf(element) == -1) {
          this.options.push(element);
        }
      });
      this.isloading = false;
    },

    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.form.targetlist.forEach((target) => {
            const temp = Object.assign({}, this.form);
            temp.target = target;
            add(temp)
              .then((v) => {
                this.getdata();
                this.$notify({
                  title: "成功",
                  message: "添加成功",
                  type: "success",
                });
                this.isDialogShow = false;
              })
              .catch((error) => {
                this.$notify.error({
                  title: "错误",
                  message: error,
                });
              });
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    handleUpdate (row) {
      this.form = Object.assign({}, row); // copy obj
      this.dialogStatus = "edit";
      this.isDialogShow = true;
      this.$nextTick(() => {
        this.$refs["form"].clearValidate();
      });
    },
    updateData () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          edit(this.form).then(() => {
            this.getdata();
            this.isDialogShow = false;
            this.$notify({
              title: "成功",
              message: "修改成功",
              type: "success",
              duration: 2000,
            });
          });
        }
      });
    },
    handleDelete (id) {
      handleCofirm("确认要删除吗？", "warning").then((res) => {
        del(id)
          .then((v) => {
            this.getdata();
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
            });
            this.isDialogShow = false;
          })
          .catch((error) => {
            this.$notify.error({
              title: "错误",
              message: error,
            });
          });
      });
    },
    open () {
      this.form = {
        area: this.nowuserarea,
        target: "",
        targetlist: [],
        receiveName: "",
        receiveDate: "",
      };
      this.dialogStatus = "add";
      this.$nextTick(() => {
        this.$refs["form"].clearValidate();
      });
      this.isDialogShow = true;
    },
  },
};
</script>
<style lang="scss" scoped>
@import "../../../public/css/table.scss";
.beian-container {
  margin: 5 px;
  background-color: #fff;
}
::v-deep .el-header {
  display: flex;
  align-items: center;
  padding: 0px 5px;
}

.item {
  margin-right: 15px;
}

.header-button {
  padding: 10px;
  display: flex;
  justify-content: space-between;
}

.header {
  font-size: 14px;
  font-weight: 600;
  line-height: 35px;
  margin-right: 5px;
  border-bottom: 1px dashed #ccc;

  i {
    color: #4778c7;
  }
}
</style>